<template>
  <div class="score-overview">
    <div class="overview-section">
      <!-- 整体概览 -->
      <div class="overview-content">
        <!-- 提交情况 -->
        <div class="submit-info">
          <!-- 单个班级情况 -->
          <div>
            <span style="font-weight: bold;">本次作业：</span>满分<i>{{ overviewData.fullScore }}分</i>，
          </div>
          <div>
            全体最高分<i>{{ formatNumber(overviewData.examHighestScore) }}分</i>，
            全体平均分<i>{{ formatNumber(overviewData.examAvgScore) }}分</i>，
            优秀率<i>{{ formatNumber(overviewData.examExcellentPercent) }}%</i>/
            及格率<i>{{ formatNumber(overviewData.examPassPercent) }}%</i>/
            中位数为<i>{{ formatNumber(overviewData.examMedianScore) }}分</i>/
            标准差为<i>{{ formatNumber(overviewData.examStdDeviation) }}</i>
          </div>
          <div>
            班最高分<i>{{ formatNumber(overviewData.highestScore) }}分</i>，
            班平均分<i>{{ formatNumber(overviewData.avgScore) }}分</i>，
            优秀率<i>{{ formatNumber(overviewData.excellentPercent) }}%</i>/
            及格率<i>{{ formatNumber(overviewData.passPercent) }}%</i>/
            中位数为<i>{{ formatNumber(overviewData.medianScore) }}分</i>/
            标准差为<i>{{ formatNumber(overviewData.stdDeviation) }}</i>
          </div>
          <div :class="{ 'collapsed': !expanded }" ref="container" style="padding-right: 50px;position: relative;">
            本班<i>{{ overviewData.totalCount }}人</i>，
            扫描<i>{{ overviewData.submitCount }}人</i>，
            缺少<i>{{ overviewData.totalCount - overviewData.submitCount }}人</i>
            ，缺少名单：
                <span ref="textContent" style="color: #8E96A4;" v-for="(item,index) in overviewData.unsubmittedList" :key="index">{{ item }}<span v-if="index != overviewData.unsubmittedList.length - 1">、</span></span>
                <span v-if="showToggle" :style="!expanded ? 'position: absolute;right: -5px;bottom: 0;' : ''" class="toggle-btn" @click="toggleExpand">
                  {{ expanded ? '收起' : '展开' }}
                </span>
            <!-- <span style="width: 80%;" class="expandable-text">
              <b v-if="overviewData.unsubmittedList?.length">
                ，缺少名单：
                <span v-for="(item,index) in overviewData.unsubmittedList" :key="index">{{ item }}卡达克来犒劳犒劳打开了打开了看得开打卡打卡来犒劳犒劳打开了打开了</span>
                <span
                  class="content"
                  :class="{ 'collapsed': !expanded }"
                  @click="toggleExpand"
                >
                  {{ overviewData.unsubmittedList.join(';') }}卡达克来犒劳犒劳打开了打开了看得开打卡打卡来犒劳犒劳打开了打开了
                </span>
                <span class="toggle-btn" @click="toggleExpand">
                  {{ expanded ? '收起' : '展开' }}
                </span>
              </b>
            </span> -->
            <!-- <b v-if="overviewData.unsubmittedList?.length">
              ，缺少名单：<i>{{ overviewData.unsubmittedList.join(';') }}</i>
            </b> -->
          </div>
          <!-- <div>
            本班<i>{{ overviewData.totalCount }}人</i>，
            扫描<i>{{ overviewData.submitCount }}人</i>，
            缺少<i>{{ overviewData.totalCount - overviewData.submitCount }}人</i>
            <div class="expandable-text">
              <b v-if="overviewData.unsubmittedList?.length" style="display: flex;width:100%">
                ，缺少名单：
                <div style="width:92%;">
                  <Expandable :text="overviewData.unsubmittedList.join('、')">
                  </Expandable>
                </div>

                <div class="container" ref="textContainer">
                  <span
                    class="content"
                    :class="{ 'collapsed': !expanded }"
                    ref="contentText"
                  >
                    {{ overviewData.unsubmittedList.join('、') }}
                  </span>
                  <a
                    href="javascript:;"
                    @click="toggleExpand"
                    style="margin-left: 5px; color: #1890ff;border: 1px solid #295CFF;background: #295cff0f;padding:0 12px;border-radius:100px;color:rgb(41, 92, 255);text-decoration: none;"
                    v-if="shouldShowToggle"
                  >
                    {{ expanded ? '收起' : '展开' }}
                  </a>
                </div>
              </b>
            </div>
          </div> -->
        </div>
      </div>
    </div>
    <!-- 1.3 成绩单 -->
    <div class="score-details anchor-offset" id="Homework-score">
      <div style="display: flex;align-items: center;justify-content: space-between;">
        <h3 class="header-with-select">成绩单</h3>
        <div @click="reportCardExport" class="derivedBtn" style="margin-bottom: 14px;margin-top: 24px;cursor: pointer;color: #295CFF;">导出</div>
      </div>
      <el-table :data="scoreDetails" :height="scoreDetails.length > 8 ? '60vh' : ''" border stripe
        :header-cell-style="{ background: '#e8f0fa', color: '#2A303B', fontWeight: '500' }" class="custom-table"
        tooltip-effect="dark" style="width: 100%">
        <!-- 固定列 - 跨两行 -->
        <!-- <el-table-column prop="class" label="班级" align="center" row-span="2" width="100" /> -->
         <el-table-column fixed="left" type="index" label="序号" align="center" width="100" />
        <el-table-column fixed="left" prop="studentNo" label="考号" align="center" width="100" />
        <el-table-column fixed="left" prop="name" label="姓名" align="center" width="100" />
        <el-table-column fixed="left" prop="gradeRank" label="全体排名" align="center"  width="100" />
        <el-table-column fixed="left" prop="rank" label="班级排名 " align="center" />
        <el-table-column fixed="left" prop="totalScore" label="总分" align="center" width="80" />
        <!-- 总分列 -->
        <el-table-column label="总得分" align="center">
          <el-table-column prop="objectiveScore" label="客观题总分" align="center" width="100" />
          <el-table-column prop="subjectiveScore" label="主观题总分" align="center" width="100" />
        </el-table-column>
        <!-- 客观题列 -->
        <el-table-column label="客观题得分" align="center">
          <template v-for="num in objectiveQuestionNums">
            <el-table-column :key="num" :label="num" align="center">
              <template slot-scope="scope">
                {{ scope.row.objectiveMap[num] }}
              </template>
            </el-table-column>
          </template>
        </el-table-column>

        <!-- 主观题列 -->
        <el-table-column label="主观题得分" align="center">
          <template v-for="num in subjectiveQuestionNums">
            <el-table-column :key="num" :label="num" align="center">
              <template slot-scope="scope">
                {{ scope.row.subjectiveMap[num] }}
              </template>
            </el-table-column>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 高频错题统计  v-if="hasData"-->
    <div class="error-questions anchor-offset" id="High-frequency-incorrect-questions">
      <div style="display: flex;align-items: center;justify-content: space-between;">
        <h3 class="header-with-select">高频错题</h3>
        <div style="margin-bottom: 14px;margin-top: 24px;cursor: pointer;color: #295CFF;display: flex;align-items: center;">
          <!-- <el-input size="small" style="width: 160px;" @input="handleInput" placeholder="请输入内容" v-model="errorQuestionRate" class="input-with-select">
            <el-button @click="changeScoringRate" slot="append" icon="el-icon-search"></el-button>
          </el-input> -->
          <el-dropdown>
            <span class="typeSymbol">
              <span v-if="highFrequencyWrongQuestionsType == 1">小于<span style="color: #B3B8C2">&le;</span></span>
              <span v-if="highFrequencyWrongQuestionsType == 2">大于<span style="color: #B3B8C2">&ge;</span></span>
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="switchingType(2)">大于&ge;</el-dropdown-item>
              <el-dropdown-item @click.native="switchingType(1)">小于&le;</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <div class="typeSymbol" style="margin-left: 10px;">
            <input @input="handleInput" style="width: 22px;" v-model="errorQuestionRate" type="text">
            <span style="margin-right: 10px;color: #B3B8C2;margin-left: 2px;font-size: 14px;">%</span>
            <i @click="changeScoringRate" style="font-size: 14px;cursor: pointer;" class="el-icon-search"></i>
          </div>
          <div @click="derivedExcel" class="derivedBtn" style="cursor: pointer;color: #295CFF;margin-left: 10px;">导出</div>
        </div>
      </div>
      <el-table :data="errorQuestions" border v-loading="loadingErrorQuestions"
        :empty-text="errorQuestionsError || '暂无数据'" stripe
        :header-cell-style="{ background: '#e8f0fa', color: '#2A303B', fontWeight: '500' }" class="custom-table"
        tooltip-effect="dark" style="width: 100%"
        :height="objectiveAnswerData.length > 11 ? '70vh': ''">
        <el-table-column prop="questionNum" label="题号" width="90" align="center" />
        <el-table-column prop="questionTypeName" label="题型" width="90" align="center" />
        <el-table-column label="知识点">
         <template slot-scope="scope">
          <Expandable :text="scope.row.knowledge"></Expandable>
            <!-- <div class="expandable-cell" style="display: flex; flex-wrap: wrap;">
                <div style="padding-right: 10px;">
                  <template v-if="scope.row.knowledge">
                    <Expandable>
                        {{scope.row.knowledge}}
                    </Expandable>
                  </template>
                </div>
              </div> -->
	      </template>
      </el-table-column>
        <el-table-column prop="scoreRate" label="班正答率/班得分率" width="140" align="center">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.scoreRate) }}%
          </template>
        </el-table-column>
        <el-table-column prop="examScoreRate" label="全体正答率/全体得分率" align="center">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.examScoreRate) }}%
          </template>
        </el-table-column>
        <el-table-column label="全对学生">
          <template slot-scope="scope">
            <span v-if="scope.row.correctlistname.length===0">-</span>
            <Expandable v-else :text="scope.row.correctlistname"></Expandable>
          </template>
        </el-table-column>
        <el-table-column prop="dimidiatelistname" label="半对学生">
            <template slot-scope="scope">
              <span v-if="scope.row.dimidiatelistname.length===0">-</span>
              <Expandable v-else :text="scope.row.dimidiatelistname"></Expandable>
          </template>
        </el-table-column>
        <el-table-column prop="errorlistname" label="错误学生">
            <template slot-scope="scope">
              <span v-if="scope.row.errorlistname.length===0">-</span>
              <Expandable v-else :text="scope.row.errorlistname"></Expandable>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div id="Objective-Question-Answering" class="anchor-offset">
      <div style="display: flex;align-items: center;justify-content: space-between;">
        <h3 class="header-with-select" style="margin-top:24px;">客观题作答分布</h3>
        <div @click="objectiveQuestionDerivation" class="derivedBtn" style="margin-bottom: 14px;margin-top: 24px;cursor: pointer;">导出</div>
      </div>
      <el-card v-loading="loadingObjectiveQuestions">
        <el-table :height="objectiveAnswerData.length > 11 ? '60vh': ''" :data="objectiveAnswerData" border stripe
          :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
          tooltip-effect="dark" style="width: 100%">
          <el-table-column prop="questionNum" label="试题" align="center" />
          <el-table-column prop="answer" label="答案" align="center" />
          <el-table-column prop="score" label="分值" align="center" />
          <el-table-column prop="avgScore" label="平均分" align="center" />
          <el-table-column prop="scoreRate" label="班正答率(%)" align="center" />
          <el-table-column prop="examScoreRate" label="全体正答率(%)" align="center" />
          <el-table-column prop="fullScoreRate" label="满分率(%)" align="center" />
          <el-table-column prop="zeroScoreRate" label="零分率(%)" align="center" />
          <el-table-column label="学生作答" align="center" width="400">
            <template slot-scope="scope">
              <ul class="studentanswer">
                <li v-for="(option, index) in scope.row.newstudentAnswer" :key="index"
                  :class="{ 'hover': option.includes(scope.row.answer) }">{{ option }}</li>
              </ul>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div id="subjective-Question-Answering" class="anchor-offset">
      <div style="display: flex;align-items: center;justify-content: space-between;">
        <h3 class="header-with-select" style="margin-top:24px;">主观题作答分布</h3>
        <div @click="subjectiveQuestionDerivation" class="derivedBtn" style="margin-bottom: 14px;margin-top: 24px;cursor: pointer;">导出</div>
      </div>
      <el-card v-loading="loadingSubjectiveQuestions">
        <el-table :height="subjectiveAnswerData.length > 11 ? '60vh': ''" :data="subjectiveAnswerData" border stripe
          :header-cell-style="{ background: '#E8F0FA', color: '#2A303B', fontWeight: '500' }" class="custom-table"
          tooltip-effect="dark" style="width: 100%">
          <el-table-column prop="questionNum" label="试题" align="center" />
          <!-- <el-table-column prop="answer" label="答案" align="center" /> -->
          <el-table-column prop="score" label="分值" align="center" />
          <el-table-column prop="avgScore" label="平均分" align="center" />
          <el-table-column prop="scoreRate" label="班得分率(%)" align="center" />
          <el-table-column prop="examScoreRate" label="全体得分率(%)" align="center" />
          <el-table-column prop="fullScoreRate" label="满分率(%)" align="center" />
          <el-table-column prop="zeroScoreRate" label="零分率(%)" align="center" />
          <el-table-column label="学生作答" align="center" width="500">
            <template slot-scope="scope">
              <ul class="studentanswer">
                <li v-for="(option, index) in scope.row.newstudentAnswer" :key="index"
                  :class="{ 'hover': isHighestPercentage1(scope.row, option) }">{{ option }}</li>
              </ul>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <!-- 上升/下降学生（仅对比前两次）-->
    <div v-if="hasData" class="rank-change anchor-offset" id="fluctuate-student">
      <h3 class="header-with-select">上升/下降学生（仅对比前两次）</h3>
      <el-table :data="rankChangeData" border v-loading="loadingRankChange" stripe
        :header-cell-style="{ background: '#e8f0fa', color: '#2A303B', fontWeight: '500' }" class="custom-table"
        :height="rankChangeData.length > 13 ? '670px' : undefined"
        tooltip-effect="dark" style="width: 100%">
        <el-table-column prop="name" label="姓名" align="center" />

        <el-table-column label="作业1得分（排名）" align="center">
          <template slot-scope="scope">
            {{ scope.row.score1 }} ({{ scope.row.rank1 }})
          </template>
        </el-table-column>

        <el-table-column label="作业2得分（排名）" align="center">
          <template slot-scope="scope">
            {{ scope.row.score2 }} ({{ scope.row.rank2 }})
          </template>
        </el-table-column>

        <el-table-column label="作业3得分（排名）" align="center" v-if="hasThirdExam">
          <template slot-scope="scope">
            {{ scope.row.score3 }} ({{ scope.row.rank3 }})
          </template>
        </el-table-column>

        <el-table-column label="得分浮动率" align="center">
          <template slot-scope="scope">
            1→2: {{ formatNumber(scope.row.scoreFluctuation1) }}%
            <template v-if="hasThirdExam">
              <br>2→3: {{ formatNumber(scope.row.scoreFluctuation2) }}%
            </template>
          </template>
        </el-table-column>

        <el-table-column label="排名浮动率" align="center">
          <template slot-scope="scope">
            1→2: {{ formatNumber(scope.row.rankFluctuation1) }}%
            <template v-if="hasThirdExam">
              <br>2→3: {{ formatNumber(scope.row.rankFluctuation2) }}%
            </template>
          </template>
        </el-table-column>

        <el-table-column prop="scoreStdDev" label="得分标准差" align="center">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.scoreStdDev) }}
          </template>
        </el-table-column>

        <el-table-column prop="rankDeviation" label="排名波动" align="center">
          <template slot-scope="scope">
            {{ formatNumber(scope.row.rankDeviation) }}
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getScoreOverview, getScoreDetails, getErrorQuestions, getRankChange,scoreDetailsExcel,getObjectiveAnswerDistribution,getSubjectiveAnswerDistribution, } from '@/api/score'
import { saveAs } from 'file-saver';
import * as XLSX from 'xlsx';
import Expandable from '@/components/expandable.vue';
export default {
  name: 'ScoreOverview',
  props: {
    examId: {
      type: String,
      required: true
    },
    classId: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      queryParams: {
        examId: '',
        classId: ''
      },
      objectiveAnswerData: [],
      subjectiveAnswerData: [],
      scoringRate: 60,
      highFrequencyWrongQuestionsType: 1,
      loading: false,
      loadingScoreDetails: false,
      loadingErrorQuestions: false,
      hasData: false,
      overviewData: {
        examHighestScore: 0,
        examAvgScore: 0,
        examExcellentPercent: 0,
        examPassPercent: 0,
        examMedianScore: 0,
        examStdDeviation: 0,
        fullScore: 0,
        highestScore: 0,
        avgScore: 0,
        excellentPercent: 0,
        passPercent: 0,
        medianScore: 0,
        stdDeviation: 0,
        totalCount: 0,
        submitCount: 0,
        unsubmittedList: []
      },
      scoreDetails: [],
      objectiveQuestionNums: [],
      subjectiveQuestionNums: [],
      errorQuestions: [],
      errorQuestionRate: 40,
      errorQuestionsError: '',
      loadingRankChange: false,
      loadingSubjectiveQuestions: false,
      loadingObjectiveQuestions: false,
      rankChangeError: '',
      rankChangeData: [],
      hasThirdExam: false,
      expanded: false,
      shouldShowToggle: false, // 是否显示 "展开/收起" 按钮
      isContentOverflow: false,
      containerWidth: 0,
      showToggle: false,
      contentWidth: 0
    }
  },

  methods: {
    checkOverflow() {
      this.$nextTick(() => {
        const container = this.$refs.container;
        const content = this.$refs.textContent;
        if (container && content) {
          // 比较内容宽度和容器宽度
          this.contentWidth = 0
          content.forEach(item => {
            console.log(item.offsetWidth);
            this.contentWidth += item.offsetWidth;
          })
          // const contentWidth = content.scrollWidth;
          const containerWidth = container.offsetWidth;
          // 只有在未展开状态下才更新showToggle
          if (!this.expanded) {
            this.showToggle = this.contentWidth > (containerWidth-290);
          }
        }
      });
    },
    checkTextOverflow() {
      // 确保 DOM 已经渲染
      this.$nextTick(() => {
        const container = this.$refs.textContainer;
        const content = this.$refs.contentText;

        if (container && content) {
          // 比较容器宽度和内容实际宽度
          this.shouldShowToggle = content.scrollWidth > container.clientWidth;
        }
      });
    },
    toggleExpand() {
      this.expanded = !this.expanded
    },
    checkContentOverflow() {
      this.$nextTick(() => {
        const container = this.$refs.contentContainer;
        if (container) {
          this.isContentOverflow = container.scrollWidth > container.clientWidth;
        }
      });
    },
    toggleExpand1(row) {
      row.expanded = !row.expanded;
      this.checkContentOverflow();
    },
    formatNumber (num) {
      if (num === undefined || num === null) return '--'
      return Number(num).toFixed(2)
    },
    derivedExcel() {
      const data = [
        ['题号', '题型', '知识点','班正答率/班得分率','全体正答率/全体得分率','全对学生','半对学生','错误学生'],
      ];
      this.errorQuestions.map(item => {
        let arr = []
        arr.push(item.questionNum)
        arr.push(item.questionTypeName)
        arr.push(item.knowledge)
        arr.push(this.formatNumber(item.scoreRate) + '%')
        arr.push(this.formatNumber(item.examScoreRate) + '%')
        arr.push(item.correctlistname)
        arr.push(item.dimidiatelistname)
        arr.push(item.errorlistname)
        data.push(arr)
      })
      console.log(XLSX,'99999999999999999999999999');
      // 创建工作簿
      // const ws = XLSX.utils.aoa_to_sheet(data);
      // const wb = XLSX.utils.book_new();
      // XLSX.utils.book_append_sheet(wb, ws, '员工信息');

      // // 生成文件并保存
      // const buffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
      // const blob = new Blob([buffer], { type: 'application/octet-stream' });
      // saveAs(blob, '员工列表.xlsx')
      // 动态计算每列最大宽度（按字符数）
      const colWidths = data[0].map((_, colIndex) => {
        return Math.max(
          ...data.map(row => {
            const cellValue = row[colIndex] || '';
            return typeof cellValue === 'string' ?
              cellValue.toString().length * 1.8 : // 中文系数
              10; // 默认宽度
          }),
          15 // 最小宽度
        );
      });

      const ws = XLSX.utils.aoa_to_sheet(data);
      ws['!cols'] = colWidths.map(w => ({ wch: w })); // 设置列宽

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '高频错题'); // 修正工作表名
      XLSX.writeFile(wb, '高频错题.xlsx'); // 直接导出文件
    },
    reportCardExport() {
      scoreDetailsExcel(Number(this.examId), Number(this.classId)).then(res => {
        if (res.code == 200) {
          const link = document.createElement('a');
          let fileName = '成绩单.xlsx'
          link.href = process.env.VUE_APP_BASE_APIS + res.data;
          link.download = fileName || 'file.xlsx'; // 设置默认文件名
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        }
      })
    },
    // 处理查询
    async handleQuery () {
      if (!this.queryParams.examId || !this.queryParams.classId) {
        this.$message.warning('请输入批次ID和班级ID')
        return
      }

      this.hasData = false
      await this.loadAllData()
    },

    // 处理重置
    handleReset () {
      this.queryParams = {
        examId: '',
        classId: ''
      }
      this.hasData = false
      this.resetData()
    },

    // 重置数据
    resetData () {
      this.overviewData = {
        fullScore: 0,
        highestScore: 0,
        avgScore: 0,
        excellentPercent: 0,
        passPercent: 0,
        medianScore: 0,
        stdDeviation: 0,
        totalCount: 0,
        submitCount: 0,
        unsubmittedList: []
      }
      this.scoreDetails = []
      this.objectiveQuestionNums = []
      this.subjectiveQuestionNums = []
      this.errorQuestions = []
      this.errorQuestionsError = ''
      this.rankChangeData = []
    },

    // 加载所有数据
    async loadAllData () {
      try {
        this.loading = true
        await Promise.all([
          this.loadErrorQuestions(),
          this.loadData(),
          this.loadScoreDetails(),
          this.loadRankChange()
        ])
        this.hasData = true
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败，请检查输入的ID是否正确')
        this.hasData = false
      } finally {
        this.loading = false
      }
    },

    // 加载成绩概览
    async loadOverview () {
      try {
        const res = await getScoreOverview(
          Number(this.examId),
          Number(this.classId)
        )
        if (res.code === 200) {
          this.overviewData = res.data
          this.$nextTick(()=> {
            this.checkOverflow();
          })
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载成绩概览失败:', error)
        throw error  // 向上传递错误，让 loadData 统一处理
      }
    },

    // 加载数据
    async loadData () {
      if (!this.examId || !this.classId) return

      try {
        this.loading = true  // 添加loading状态
        await Promise.all([
          this.loadOverview(),
          this.loadScoreDetails(),
          this.loadErrorQuestions(),
          this.loadRankChange(),
          this.getObjectiveQuestions(),
          this.getSubjectiveQuestions()
        ])

        this.hasData = true
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载数据失败')
        this.hasData = false
      } finally {
        this.loading = false
      }
    },

    // 加载作业得分表
    async loadScoreDetails () {
      try {
        this.loadingScoreDetails = true
        const res = await getScoreDetails(
          Number(this.examId),
          Number(this.classId)
        )
        if (res.code === 200) {
          this.scoreDetails = res.data
          if (this.scoreDetails.length > 0) {
            const firstStudent = this.scoreDetails[0]
            this.objectiveQuestionNums = Object.keys(firstStudent.objectiveMap || {})
              .sort((a, b) => Number(a) - Number(b))
            this.subjectiveQuestionNums = Object.keys(firstStudent.subjectiveMap || {})
              .sort((a, b) => Number(a) - Number(b))
          }
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载作业得分表失败:', error)
        throw error  // 向上传递错误
      } finally {
        this.loadingScoreDetails = false
      }
    },
    switchingType(e) {
      this.highFrequencyWrongQuestionsType = e
      this.loadErrorQuestions()
    },
    handleInput(value) {
      // 使用正则表达式匹配非数字内容
      if (/[^\d]/.test(this.errorQuestionRate)) {
        // 如果包含非数字内容，清空表单并提示
        this.errorQuestionRate = '';
        this.$message.error('请输入数字');
      }
    },
    changeScoringRate() {
      this.loadErrorQuestions()
    },
    // 加载高频错题统计
    async loadErrorQuestions () {
      try {
        this.loadingErrorQuestions = true
        this.errorQuestionsError = ''

        const res = await getErrorQuestions(
          Number(this.examId),
          Number(this.classId),
          Number(this.errorQuestionRate),
          this.highFrequencyWrongQuestionsType
        )
        if (res.code === 200) {
          res.data.forEach(item => {
            // 初始化三个数组来存储不同类型的名单
            item.errorlistname = [];
            item.correctlistname = [];
            item.dimidiatelistname = [];

            // 遍历 rights 数组
            item.answerRight.rights.forEach(right => {
              const students = right.studentList.join(', '); // 将学生名字用逗号连接成一个字符串
              switch (right.isRight) {
                case "0": // 错误
                  item.errorlistname.push(students); // 将字符串添加到 errorlistname
                  break;
                case "1": // 正确
                  item.correctlistname.push(students); // 将字符串添加到 correctlistname
                  break;
                case "2": // 半对
                  item.dimidiatelistname.push(students); // 将字符串添加到 dimidiatelistname
                  break;
                default:
                  break;
              }
            });

            // 将数组中的字符串用逗号连接成一个完整的字符串
            item.errorlistname = item.errorlistname.join(', ');
            item.correctlistname = item.correctlistname.join(', ');
            item.dimidiatelistname = item.dimidiatelistname.join(', ');
          });
          this.errorQuestions = res.data || []
          console.info('this.errorQuestions', this.errorQuestions)
          if (this.errorQuestions.length === 0) {
            this.errorQuestionsError = `暂无得分率低于${this.errorQuestionRate}%的题目`
          }
        } else {
          this.errorQuestionsError = res.message || '获取高频错题统计失败'
          throw new Error(this.errorQuestionsError)
        }
      } catch (error) {
        console.error('获取高频错题统计失败:', error)
        throw error  // 向上传递错误
      } finally {
        this.loadingErrorQuestions = false
      }
    },
    async getSubjectiveQuestions () {
      try {
        this.loadingSubjectiveQuestions = true
        const res = await getSubjectiveAnswerDistribution(Number(this.examId),Number(this.classId))
        if (res.code == 200) {
          this.subjectiveAnswerData = res.data.map(item => ({
            ...item,
            newstudentAnswer: item.studentAnswer.split(' ').map(item => item.trim())
          }));
          console.log(this.subjectiveAnswerData,'(((((((((((())))))))))))')
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载主观题作答分布波动数据失败:', error)
        this.rankChangeError = '加载主观题作答分布数据失败'
        throw error  // 向上传递错误
      } finally {
        this.loadingSubjectiveQuestions = false
      }
    },
    async getObjectiveQuestions () {
      try {
        this.loadingObjectiveQuestions = true
        const res = await getObjectiveAnswerDistribution(Number(this.examId),Number(this.classId))
        if (res.code == 200) {
          this.objectiveAnswerData = res.data.map(item => ({
            ...item,
            newstudentAnswer: item.studentAnswer.split(' ').map(item => item.trim())
          }));
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载客观题作答分布波动数据失败:', error)
        this.rankChangeError = '加载客观题作答分布数据失败'
        throw error  // 向上传递错误
      } finally {
        this.loadingObjectiveQuestions = false
      }
    },
    objectiveQuestionDerivation() {
      const data = [
        ['试题', '答案', '分值','平均分','班正答率(%)','全体正答率(%)','满分率(%)','零分率(%)','学生作答'],
      ];
      this.objectiveAnswerData.map(item => {
        let arr = []
        arr.push(item.questionNum)
        arr.push(item.answer)
        arr.push(item.score)
        arr.push(item.avgScore)
        arr.push(item.scoreRate)
        arr.push(item.examScoreRate)
        arr.push(item.fullScoreRate)
        arr.push(item.zeroScoreRate)
        arr.push(item.newstudentAnswer.join(','))
        data.push(arr)
      })
      console.log(XLSX,'99999999999999999999999999');
      const colWidths = data[0].map((_, colIndex) => {
        return Math.max(
          ...data.map(row => {
            const cellValue = row[colIndex] || '';
            return typeof cellValue === 'string' ?
              cellValue.toString().length * 1.8 : // 中文系数
              10; // 默认宽度
          }),
          15 // 最小宽度
        );
      });

      const ws = XLSX.utils.aoa_to_sheet(data);
      ws['!cols'] = colWidths.map(w => ({ wch: w })); // 设置列宽

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '客观题作答分布'); // 修正工作表名
      XLSX.writeFile(wb, '客观题作答分布.xlsx'); // 直接导出文件
    },
    subjectiveQuestionDerivation() {
      const data = [
        ['试题', '分值','平均分','班得分率(%)','全体得分率(%)','满分率(%)','零分率(%)','学生作答'],
      ];
      this.subjectiveAnswerData.map(item => {
        let arr = []
        arr.push(item.questionNum)
        arr.push(item.score)
        arr.push(item.avgScore)
        arr.push(item.scoreRate)
        arr.push(item.examScoreRate)
        arr.push(item.fullScoreRate)
        arr.push(item.zeroScoreRate)
        arr.push(item.newstudentAnswer.join(','))
        data.push(arr)
      })
      console.log(XLSX,'99999999999999999999999999');
      const colWidths = data[0].map((_, colIndex) => {
        return Math.max(
          ...data.map(row => {
            const cellValue = row[colIndex] || '';
            return typeof cellValue === 'string' ?
              cellValue.toString().length * 1.8 : // 中文系数
              10; // 默认宽度
          }),
          15 // 最小宽度
        );
      });

      const ws = XLSX.utils.aoa_to_sheet(data);
      ws['!cols'] = colWidths.map(w => ({ wch: w })); // 设置列宽

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, '主观题作答分布'); // 修正工作表名
      XLSX.writeFile(wb, '主观题作答分布.xlsx'); // 直接导出文件
    },
    async loadRankChange () {
      try {
        this.loadingRankChange = true
        this.rankChangeError = ''
        const res = await getRankChange(Number(this.examId), Number(this.classId))
        if (res.code === 200) {
          this.rankChangeData = res.data.changes || []
          this.hasThirdExam = this.rankChangeData.some(item => item.score3 !== undefined)
        } else {
          throw new Error(res.message)
        }
      } catch (error) {
        console.error('加载成绩波动数据失败:', error)
        this.rankChangeError = '加载成绩波动数据失败'
        throw error  // 向上传递错误
      } finally {
        this.loadingRankChange = false
      }
    },
    isHighestPercentage (row, option) {
      console.info('row', row)
      console.info('option', option)
      const options = row.newstudentAnswer;
      const correctAnswer = row.answer;

      // 提取每个选项的百分比
      const percentages = options.map(opt => {
        const match = opt.match(/\((\d+\.\d+)%\)/);
        return match ? parseFloat(match[1]) : 0;
      });

      // 找出与正确答案不同的选项
      const incorrectOptions = options.filter(opt => !opt.includes(correctAnswer));

      // 找出占比最高的选项
      const maxPercentage = Math.max(...percentages);

      // 判断当前选项是否是占比最高的且不是正确答案
      return option.includes(correctAnswer) ? false : percentages[options.indexOf(option)] === maxPercentage;
    },
    isHighestPercentage1 (row, option) {
      const options = row.newstudentAnswer;

      // 提取每个选项的百分比
      const percentages = options.map(opt => {
        const match = opt.match(/\((\d+\.\d+)%\)/);
        return match ? parseFloat(match[1]) : 0;
      });


      // 找出占比最高的选项
      const maxPercentage = Math.max(...percentages);

      // 判断当前选项是否是占比最高的且不是正确答案
      return percentages[options.indexOf(option)] === maxPercentage;
    }
  },

  mounted () {
    window.addEventListener('resize', this.checkOverflow);
    this.checkContentOverflow();
    this.checkTextOverflow();
    this.loadData()
    document.querySelector('.anchor-offset').addEventListener('click', () => {
      const section = document.getElementById('section2');
      section.scrollIntoView({
        behavior: 'smooth',
        block: 'start', // 或 'center'
        inline: 'nearest'
      });

      // 手动偏移
      window.scrollBy(0, -80);
    });
  },
  components: {
    Expandable
  },
  beforeDestroy () {
    if (this.boxPlotChart) {
      this.boxPlotChart.dispose()
    }
    window.removeEventListener('resize', this.checkOverflow);
  },
  watch: {
    // 监听数据变化，重新检测溢出
    'overviewData.unsubmittedList'() {
      this.checkTextOverflow();
    },
    overviewData: {
      handler() {
        this.$nextTick(()=> {
            this.checkOverflow();
          })
      }, deep: true
    }
  }
}
</script>

<style scoped>
.score-overview {
  background: #FFFFFF;
  box-shadow: 0 4px 16px 0 #5572921a;
  border-radius: 10px;
  padding: 24px;
}

.query-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.query-form {
  display: flex;
  align-items: center;
}

.overview-section,
.score-details,
.score-analysis,
.rank-change,
.error-questions {
  background: #fff;
  border-radius: 4px;
}

.overview-content {
  box-sizing: border-box;
  background: #295cff0a;
  border: 1px solid #295cff33;
  border-radius: 10px;
  padding: 18px 24px 0;
  font-size: 14px;
}

.submit-info {
  margin-bottom: 16px;
  line-height: 1.8;
  color: #8E96A4
}

.submit-info span {
  color:#5b6371
}

.submit-info i {
  color: #5B6371;
  font-style: normal;
}

.submit-info b {
  font-style: normal;
  font-weight: normal;
}

.class-info {
  margin-top: 8px;
  text-indent: 2em;
  line-height: 1.8;
}

.score-row {
  display: flex;
  gap: 16px;
  justify-content: center;
}

.score-item {
  min-width: 40px;
  text-align: center;
}

.question-numbers {
  display: flex;
  gap: 16px;
  justify-content: center;
  margin-top: 8px;
  font-size: 12px;
}

.question-numbers span {
  min-width: 40px;
  text-align: center;
}

.rank-change {
  background: #fff;
  border-radius: 4px;
}

.change-info {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.change-info .el-tag {
  min-width: 80px;
}

.error-questions {
  background: #fff;
  border-radius: 4px;
}

.el-tag {
  width: 80px;
  text-align: center;
}

.analysis-content {
  margin-top: 16px;
  line-height: 1.8;
}

.header-with-select {
  font-size: 16px;
  color: #2A303B;
  margin-bottom: 14px;
  margin-top: 24px;
}

.custom-table {
  width: 100%;
  border: 1px solid rgba(216, 228, 240, 1);
  border-radius: 10px;
  border-right: none;
  border-bottom: none;
}

/* 自定义表格内部元素的样式 */
.custom-table>>>.el-table__header-wrapper th {
  background-color: rgb(232, 240, 250);
  height: 42px;
  padding: 0;
  text-align: center;
  font-weight: normal
}

.custom-table>>>.el-table__row td {
  height: 42px;
  padding: 0;
  text-align: center;
  border-bottom: none;
  border-right: solid 1px rgba(216, 228, 240, 1);
}

.el-table .warning-row {
  background: #ffffff;
}

.el-table .success-row {
  background: #D8E4F0;
}
</style>
<style>
.el-table th {
  border-color: rgba(216, 228, 240, 1) !important;
}
.derivedBtn {
  padding: 2px 12px;
  border-radius: 100px;
  color: #295CFF;
  border: 1px solid #295CFF;
  background: #295cff0f;
}
.typeSymbol {
  display: flex;
  align-items: center;
  border: 1px solid #DEE1E7;
  background: #F5F6F8;
  border-radius: 100px;
  padding: 3px 13px;
  color: #5b6371;
}
.typeSymbol input {
  border: none;
  background-color: #F5F6F8;
  outline: none;
  text-align: right;
  color: #5b6371;
}
.anchor-offset {
  scroll-margin-top: 50px;
}
.expandable-cell {
  position: relative;
  display: flex;
  flex-wrap: wrap;
}
.studentanswer{
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	padding:4px 0;
}
.studentanswer li{
	background:rgb(242, 244, 251);
	border:solid 1px rgb(216, 225, 255);
	height: 30px;
	border-radius: 10px;
	font-size:14px;
	color:#295CFF;
	padding:0 14px;
	line-height:30px;
	margin:4px 7px;
}
.studentanswer li.hover{
	background:rgb(250, 243, 245);
	border:solid 1px rgb(247, 212, 215);
	color:#EC555A;
}
.collapsed {
  display: -webkit-box;
  -webkit-line-clamp: 1; /* 限制显示行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
/* .toggle-btn {
  color: #1890ff !important;
  cursor: pointer;
  margin-left: 4px;
  user-select: none;
} */
.toggle-btn {
  color: #1890ff !important;
  height:20px;
  line-height:18px;
  cursor: pointer;
  border: 1px solid #295CFF;
  background: #295cff0f;
  padding:0 10px;
  border-radius:100px;
  color:rgb(41, 92, 255);
  text-decoration: none;
  font-size:12px;
}
/* .toggle-btn:hover {
  text-decoration: underline;
} */
</style>
